#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include "log.hpp"

using namespace std;

const int size = 4096;
const string pathname = "/home/xny";
const int proj_id = 0x7777;
Log log;

key_t Getkey()
{
    key_t k = ftok(pathname.c_str(), proj_id);
    if(k < 0)
    {
        log(Fatal, "ftok error: %s", strerror(errno));
        exit(1);
    }
    log(Info, "ftok success, key is: %d", k);

    return k;
}
 
int GetShareMemHelper(int flag)
{
    key_t k = Getkey();
    int shmid = shmget(k, size, flag);
    if(shmid < 0)
    {
        log(Fatal, "create share memory error: %s", strerror(errno));
        exit(2);
    }
    log(Info, "create share memory success, shmid: %d", shmid);

    return shmid;
}

// 创建共享内存
int CreateMem()
{
    return GetShareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}

// 获取共享内存
int GetMem()
{
    return GetShareMemHelper(IPC_CREAT); 
} 



#endif